package com.UBC417.termproject.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.UBC417.termproject.Data.*;
import com.google.appengine.api.datastore.EntityNotFoundException;

@SuppressWarnings("serial")
public class SearchItemServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(SubscribeServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		HttpSession session = req.getSession();
		String id= (String)session.getAttribute("id");
		
		
		String keyword = req.getParameter("keyword");
		log.info("search word: "+ keyword);
		

		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out= resp.getWriter();
		out.println("You searched: \""+keyword+"\"<br>"); 
		
		List<Item> entries = Buyer.SearchItem(keyword);
		
		if (entries.size()==0){
			//no results
			out.println("NO RESULTS!");
		}else{
			resp.getWriter().println("<table border='1'>");
			out.println("<tr>");
			out.println("<td>Item Name</td>");
			out.println("<td>Seller</td>");
			out.println("<td>Base Price</td>");
			out.println("<td>Start Date</td>");
			out.println("<td>End Date</td>");
			out.println("<td>Status</td>");
			out.println("<td>Highest Bid</td>");
			//out.println("<td>Auction ID</td>");
			out.println("<td>Bid</td>");
			out.println("</tr>");
			for (Item e : entries){
				try {
					Auction a = User.getAuctionInfo(e.getAuctionId());
					Bid b= User.getHighestBid(e.getAuctionId());
					out.println("<tr>");
					out.println("<td>"+e.getName()+"</td>");
					out.println("<td><a>"+a.getUserId()+"</a></td>");
					out.println("<td>"+e.getBasePrice()+"</td>");
					out.println("<td>"+a.getStartTime()+"</td>");
					out.println("<td>"+a.getEndTime()+"</td>");
					out.println("<td>"+a.getStatus()+"</td>");
					out.println("<td>"+b.getPrice()+"</td>");
					//out.println("<td>"+e.getAuctionId()+"</td>");
					out.println("<td><input type='button' id= '"+e.getAuctionId()+"' data-bp='"+e.getBasePrice()+"' data-hp='"+b.getPrice()+"' onclick= 'bidItem(this)' value='Bid Now'/input></td>");
					out.println("</tr>");
				} catch (EntityNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			out.println("</table>");
		
		}

	}	
	
}